package com.simple.framework.utils;

import com.simple.business.domain.enumeration.ThirdAuthenticationEnum;
import com.simple.business.domain.properties.ThirdLoginProperties;
import com.simple.business.service.sms.WeixinMPService;
import com.simple.framework.config.WeiXinLoginAuthRequest;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.request.AuthRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ThirdLoginUtils implements InitializingBean {
    @Resource
    ThirdLoginProperties thirdLoginProperties;
    @Resource
    WeixinMPService weixinMPService;
    private static final Map<ThirdAuthenticationEnum, AuthRequest> requestMap = new HashMap<>();

    private void ref(){
        List<ThirdLoginProperties.ThirdLogin> thirdLogin = thirdLoginProperties.getThirdLogin();
        thirdLogin.forEach(o->{
            AuthConfig authConfig = AuthConfig.builder()
                    .clientId(o.getClientId())
                    .clientSecret(o.getClientSecret())
                    .ignoreCheckRedirectUri(true)
                    .ignoreCheckState(true)
                    .build();
            if(o.getType().equals(ThirdAuthenticationEnum.WEI_XIN.getProviderName())
                    || o.getType().equals(ThirdAuthenticationEnum.WEI_XIN_MINIPROGRAM.getProviderName())){
                ThirdAuthenticationEnum enumV = ThirdAuthenticationEnum.getEnum(o.getType());
                AuthRequest authRequest = new WeiXinLoginAuthRequest(authConfig,enumV);
                requestMap.put(enumV,authRequest);
            }
        });
        requestMap.put(ThirdAuthenticationEnum.WEI_XIN_MP,weixinMPService);
    }

    public static AuthRequest getAuthRequest(ThirdAuthenticationEnum thirdAuthenticationEnum){
        return requestMap.get(thirdAuthenticationEnum);
    }

    public static String wxSHA1(String token, String timestamp, String nonce){
        String[] array = new String[] { token, timestamp, nonce };
        Arrays.sort(array);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            sb.append(array[i]);
        }
        return DigestUtils.sha1Hex(sb.toString());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ref();
    }
}
